package com.kindnesslibrary.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.kindnesslibrary.R;
import com.kindnesslibrary.base.BaseHandler;

/**
 * Created by Administrator on 2017/7/27 0027.
 * 包括懒加载等操作
 */
public abstract class BasePageFragment extends Fragment {

    protected boolean isViewInitiated;
    protected boolean isVisibleToUser;
    protected boolean isDataInitiated;
    protected boolean isLoadLayout;
    protected View rootView;

    protected BaseHandler handler;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewInitiated = true;
        initHandler();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {
            View root = inflater.inflate(initLayout(), null);
            setRootView(root);
        }
        return getRootView();
    }

    /**
     * 懒加载
     *
     * @param isVisibleToUser
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        prepareFetchData();
    }

    protected abstract int getLayoutId();

    protected abstract void initWidget(View rootView);

    protected abstract void initData();

    protected abstract void bindEven();

    public abstract void lazyLoad(); // 懒加载

    protected abstract void handlerMessage(Message msg); // 处理handler消息

    public View getRootView() {
        return rootView;
    }

    public void setRootView(View rootView) {
        this.rootView = rootView;
    }

    protected int initLayout() {
        return R.layout.default_fragment_layout;
    }

    public <T extends View> T getViewById(int viewId){
        return (T) rootView.findViewById(viewId);
    }

    public boolean prepareFetchData() {
        return prepareFetchData(false);
    }

    public boolean prepareFetchData(boolean forceUpdate) {
        if (!forceUpdate && isVisibleToUser && !isLoadLayout) {
            if(rootView != null){
                setContentView();
            }else{
                new Handler().post(() -> {
                    if(rootView != null){
                        setContentView();
                    }
                });
                return false;
            }
        }
        if (isVisibleToUser && isViewInitiated && (!isDataInitiated || forceUpdate)) {
            lazyLoad();
            isDataInitiated = true;
            return true;
        }
        return false;
    }

    private void setContentView(){
        int childrenView = getLayoutId();
        if (childrenView == 0) {
            return;
        }
        FrameLayout mContainLayout = (FrameLayout) rootView.findViewById(R.id.fragment_contain_layout);
        LayoutInflater.from(getActivity()).inflate(childrenView, mContainLayout, true);
        isLoadLayout = true;
        initWidget(getRootView());
        initData();
        bindEven();
    }

    private void initHandler(){
        if(handler == null && getActivity() != null)
            handler = new BaseHandler(getActivity()) {
                @Override
                protected void handleMessage(Context mContext, Message msg) {
                    BasePageFragment.this.handlerMessage(msg);
                }
            };
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != rootView && rootView.getParent() != null) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
        // 将之前处理的消息移除，以免内存泄漏
        handler.removeCallbacksAndMessages(null);
        handler = null;
        System.gc();
    }
}
